package cn.dl.com;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.nio.file.Paths;

/**
 * @Author: dlc
 * @Date: 2022/1/11 - 17:56
 * 查询句子
 */
public class SentenceQuery {

    public static void main(String[] args) throws Exception{

        // 构建索引所在的路径
        String url = "C:\\mycode\\me\\gitee\\elasticstack\\demo01_lucene\\src\\main\\resources\\index";
        // 构建索引读取器
        DirectoryReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(url)));

        // 构建查询器
        IndexSearcher indexSearcher = new IndexSearcher(reader);

        // 构建查询(先将查询条件通过ik进行分词)
        QueryParser queryParser = new QueryParser("content", new IKAnalyzer());
        TopDocs topDocs = indexSearcher.search(queryParser.parse("人生是一条河"), 50);

        // 遍历文档
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for(ScoreDoc scoreDoc: scoreDocs) {
            // 获取到对应的document，通过doc获取
            Document document = indexSearcher.doc(scoreDoc.doc);
            System.out.println("-------------------------------");
            System.out.println("file_name: " + document.get("file_name"));
            System.out.println("content: " + document.get("content"));
            System.out.println("path: " + document.get("path"));
        }
        // 关闭索引读取器
        reader.close();
    }
}
